<script setup lang="ts">
import {
  computed,
  nextTick,
  onMounted,
  PropType,
  reactive,
  Ref,
  ref,
  watch,
} from 'vue';
import { useBooleanStore } from '@/store';
import { done } from 'nprogress';
import dayjs from 'dayjs';
import { getStocktakingSave, getMaterialsByLane } from '@/api/stocktaking';
import { Notification, TableRowSelection } from '@arco-design/web-vue';
import { getName, getUserJob } from '@/utils/auth';
import { LocationTypeOption, SelectdStringptionRoad } from '@/api/les/types';

const props = defineProps({
  stocktakingTypeOptions: Array as PropType<LocationTypeOption[]>,
  statusOptions: Array as PropType<LocationTypeOption[]>,
  trayOptions: Array as PropType<SelectdStringptionRoad[]>,
  largeLocationOptions: Array as PropType<any[]>,
});

const showDrawer = ref<boolean>(false);
const formRef = ref<any>();
const booleanStore = useBooleanStore();
const title = ref<string>('盘点计划');
const largeLocationOption = ref<any[] | undefined>([]);
const trayOption = ref<SelectdStringptionRoad[]>([]);
const materialsOption = ref<LocationTypeOption[]>([]);
const modalVisible = ref<boolean>(false);
const searchQuery = ref<string>('');
const currentPage = ref<number>(1);
const pageSize = ref<number>(10);
const total = ref<number>(0);
const filteredTrayOptions = ref<{ label: string; value: string }[]>([]);

const formModel = reactive({
  id: undefined,
  code: '',
  type: '',
  isLarge: 0,
  planDate: '',
  finishedDate: '',
  laneCode: undefined,
  locationCode: undefined,
  trayCode: '',
  machineType: '',
  materialCode: '',
  ratio: undefined,
  status: 1,
  remarks: '',
  createUser: '',
  createTime: '',
  updateUser: '',
  updateTime: '',
  materials: [] as string[],
  trayCodesArray: [] as string[],
});

const displayedTrayCodes = computed(() => {
  return formModel.trayCodesArray.slice(0, 2);
});

const rules = {
  type: [
    {
      required: true,
      message: '请选择盘点类型',
    },
  ],
  planDate: [
    {
      required: true,
      message: '请选择计划日期',
    },
  ],
  finishedDate: [
    {
      required: true,
      message: '请选择完成日期',
    },
  ],
  laneCode: [
    {
      required: true,
      message: '请选择巷道',
    },
  ],
  trayCode: [
    {
      required: true,
      message: '请选择托盘/箱号',
    },
  ],
  machineType: [
    {
      required: true,
      message: '请选择机型',
    },
  ],
  locationCode: [
    {
      required: true,
      message: '请选择库位',
    },
  ],
  ratio: [
    // {
    //   pattern: /^(100(\.0{1,2})?|[0-9]{1,2}(\.[0-9]{1,2})?)$/,
    //   message: '请输入0到100之间的数字,最多两位小数',
    //   trigger: 'change',
    // },
    {
      required: true,
      message: '请输入抽成比例',
    },
  ],
  materials: [
    {
      required: true,
      message: '请选择物料',
    },
  ],
};

onMounted(() => {
  // getMachineTypes();
});

const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    slotName: 'index',
    key: 'index',
  },
  {
    title: '箱号',
    dataIndex: 'label',
    key: 'label',
  },
];

// const filteredTrayOptions = computed(() =>
//   trayOption.value.filter((item) =>
//     item.label.toLowerCase().includes(searchQuery.value.toLowerCase())
//   )
// );

function handlePageChange(e: any) {
  currentPage.value = e;
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  filteredTrayOptions.value = trayOption.value.slice(start, end);
}
function handleChangeSize(e: any) {
  pageSize.value = e;
}

const selectedKeys = ref<string[]>();
const selectedRow = ref<string[]>([]);
const rowSelection = reactive({
  type: 'checkbox' as const,
  showCheckedAll: true,
  onlyCurrent: false,
});

function afterVisibleChange(val: any) {
  if (!val) {
    booleanStore.toggleBool(116);
  }
}

function isLargeChange(val: any) {
  formModel.trayCode = '';
  formModel.trayCodesArray = [];
  formModel.locationCode = undefined;
  formModel.materials = [];
  if (val === 1) {
    trayOption.value = [];
    largeLocationOption.value = props.largeLocationOptions;
  } else {
    largeLocationOption.value = [];
    trayOption.value =
      props.trayOptions?.map((item) => ({
        label: item.label,
        value: item.value,
      })) || [];
  }
}

async function locationCodeChange(val: any) {
  if (val === '') return;
  formModel.materials = [];
  const data = await getMaterialsByLane({ locationCode: val });
  if (data.retCode === '200') {
    materialsOption.value =
      data.responseBody.map((item: { value: string | any[]; label: any }) => ({
        label: item.value.concat('-', item.label),
        value: item.value,
      })) || [];
  } else {
    Notification.error({
      title: '物料查询失败',
      content: data.message,
      closable: true,
    });
  }
}

function handleCancel() {
  formRef.value?.resetFields();
  Object.assign(formModel, {
    id: undefined,
    code: '',
    type: '',
    isLarge: 0,
    planDate: '',
    finishedDate: '',
    laneCode: undefined,
    locationCode: undefined,
    machineType: '',
    materialCode: '',
    ratio: undefined,
    status: 1,
    remarks: '',
    createUser: '',
    createTime: '',
    updateUser: '',
    updateTime: '',
    materials: [] as string[],
    trayCodesArray: [] as string[],
  });
  booleanStore.toggleBool(116);
}

function modalHandleCancel() {
  selectedKeys.value = [];
  selectedRow.value = [];
  searchQuery.value = '';
  modalVisible.value = false;
}

async function handleOk() {
  const res = await formRef.value.validate();
  if (res) {
    done(false);
    return;
  }
  if (title.value === '新增盘点计划')
    formModel.createUser = getName() as string;
  else formModel.updateUser = getName() as string;
  const data = await getStocktakingSave(formModel);
  if (data.retCode === '200') {
    Notification.success({
      title: '成功',
      content: data.message,
      closable: true,
    });
    booleanStore.toggleBool(116);
    booleanStore.watchUpdate(115);
    Object.assign(formModel, {
      id: undefined,
      code: '',
      type: '',
      isLarge: 0,
      planDate: '',
      finishedDate: '',
      laneCode: undefined,
      locationCode: undefined,
      machineType: '',
      materialCode: '',
      ratio: undefined,
      status: 1,
      remarks: '',
      createUser: '',
      createTime: '',
      updateUser: '',
      updateTime: '',
      materials: [],
    });
    done();
  } else {
    Notification.error({
      title: '失败',
      content: data.message,
      closable: true,
    });
  }
}

function modalHandleOk() {
  if (selectedRow.value.length > 0) {
    formModel.trayCodesArray = selectedRow.value;
    formModel.trayCode = formModel.trayCodesArray.join(',');
    selectedKeys.value = [];
    selectedRow.value = [];
    searchQuery.value = '';
    modalVisible.value = false;
  } else {
    Notification.warning({
      title: '警告',
      content: '请选择托盘/箱号',
      closable: true,
    });
  }
}

function openModal() {
  modalVisible.value = true;
  total.value = trayOption.value.length;
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  filteredTrayOptions.value = trayOption.value.slice(start, end);
  selectedKeys.value = formModel.trayCodesArray;
}

function handleSearch() {
  const filtered = trayOption.value.filter((item) =>
    item.label.toLowerCase().includes(searchQuery.value.toLowerCase())
  );
  total.value = filtered.length;
  currentPage.value = 1;
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  filteredTrayOptions.value = filtered.slice(start, end);
}

// 监听弹框
watch(
  () => booleanStore.boolValue,
  (newValue: boolean) => {
    if (!newValue) {
      showDrawer.value = newValue;
      return;
    }
    nextTick();
    isLargeChange(formModel.isLarge);
    if (booleanStore.num === 116) {
      title.value = '新增盘点计划';
      showDrawer.value = newValue;
    } else if (booleanStore.num === 117) {
      title.value = '编辑盘点计划';
      largeLocationOption.value = props.largeLocationOptions;
      Object.assign(formModel, booleanStore.row);
      if (formModel.isLarge === 1) {
        locationCodeChange(formModel.locationCode);
      }
      formModel.materials = booleanStore.row.materials;
      showDrawer.value = newValue;
    }
  }
);

watch(selectedKeys, (newKeys) => {
  if (newKeys && newKeys.length > 0) {
    // 使用 Set 去重，确保所有选中的托盘/箱号唯一
    const allSelected = newKeys;// new Set([...selectedRow.value, ...newKeys]);
    selectedRow.value = Array.from(allSelected);
  } else {
    selectedRow.value = [];
  }
});
</script>

<template>
  <a-drawer
    width="35%"
    :height="340"
    :visible="showDrawer"
    placement="right"
    @after-visible-change="afterVisibleChange"
    @cancel="handleCancel"
    @before-ok="handleOk"
  >
    <template #title> {{ title }} </template>
    <a-form ref="formRef" :model="formModel" :rules="rules">
      <a-form-item label="是否大件" field="isLarge">
        <a-radio-group v-model="formModel.isLarge" @change="isLargeChange">
          <a-radio :value="0">否</a-radio>
          <a-radio :value="1">是</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="盘点类型" field="type">
        <a-select
          v-model="formModel.type"
          placeholder="请选择盘点类型"
          style="width: 90%"
          :options="props.stocktakingTypeOptions"
        ></a-select>
      </a-form-item>
      <a-form-item label="计划日期" field="planDate">
        <a-date-picker
          v-model="formModel.planDate"
          style="width: 90%"
          :disabledDate="
            (current) => dayjs(current).isBefore(dayjs().startOf('day'))
          "
        />
      </a-form-item>
      <a-form-item label="完成日期" field="finishedDate">
        <a-date-picker
          v-model="formModel.finishedDate"
          style="width: 90%"
          :disabledDate="
            (current) => dayjs(current).isBefore(dayjs().startOf('day'))
          "
        />
      </a-form-item>
      <a-form-item label="抽成比例" field="ratio">
        <a-input-number
          v-model="formModel.ratio"
          style="width: 90%"
          placeholder="请输入抽成比例"
          :min="0.01"
          :max="100"
          :precision="2"
        >
          <template #suffix> % </template>
        </a-input-number>
      </a-form-item>
      <!-- <a-form-item
        label="托盘/箱号"
        field="trayCode"
        v-if="formModel.isLarge === 0"
      >
        <a-input-search
          v-model="trayCodes"
          allow-clear
          readonly
          :scrollbar="true"
          style="width: 88%"
          search-button
          placeholder="请选择托盘/箱号"
        >
          <template #button-icon>
            <a-button type="primary" @click="openModal">
              <icon-plus />
            </a-button> </template
        ></a-input-search>
      </a-form-item> -->
      <a-form-item
        label="托盘/箱号"
        field="trayCode"
        v-if="formModel.isLarge === 0"
      >
        <a-input-search
          readonly
          :scrollbar="true"
          style="width: 88%"
          search-button
          :placeholder="formModel.trayCodesArray.length === 0 ? '请选择托盘/箱号' : ''"
        >
          <template #button-icon>
            <a-button type="primary" @click="openModal">
              <icon-plus />
            </a-button>
          </template>
          <template #prefix>
            <div style="display: flex; align-items: center; margin-right: 8px">
              <a-tag
                v-for="(code, index) in displayedTrayCodes"
                :key="index"
                style="margin-right: 4px"
                color="blue"
              >
                {{ code }}
              </a-tag>
              <a-tag v-if="formModel.trayCodesArray.length > 2" color="blue">
                +{{ formModel.trayCodesArray.length - 2 }}
              </a-tag>
            </div>
          </template>
          <template #suffix>
            <span v-if="formModel.trayCodesArray.length === 0" style="flex-grow: 1"></span>
          </template>
        </a-input-search>
      </a-form-item>
      <a-form-item
        label="库位"
        field="locationCode"
        v-if="formModel.isLarge === 1"
      >
        <a-cascader
          v-model="formModel.locationCode"
          :options="largeLocationOption"
          allow-search
          allow-clear
          :scrollbar="true"
          style="width: 90%"
          placeholder="请选择库位"
          @change="locationCodeChange"
        />
      </a-form-item>
      <a-form-item
        label="物料"
        field="materials"
        v-if="formModel.isLarge === 1"
      >
        <a-select
          v-model="formModel.materials"
          multiple
          :options="materialsOption"
          :max-tag-count="3"
          allow-search
          allow-clear
          :scrollbar="true"
          style="width: 90%"
          placeholder="请选择物料"
        />
      </a-form-item>
      <a-form-item label="备注" field="remarks">
        <a-textarea
          placeholder="请输入备注"
          v-model="formModel.remarks"
          :max-length="128"
          allow-clear
          show-word-limit
          style="width: 90%"
        />
      </a-form-item>
    </a-form>
    <!-- <template #footer>
      <div class="flex-btn">
        <a-button type="primary" @click="handleOk">确认</a-button>
        <a-button class="btn-reset" @click="handleCancel">取消</a-button>
      </div>
    </template> -->
  </a-drawer>
  <a-modal
    v-model:visible="modalVisible"
    title="托盘/箱号选择"
    @cancel="modalHandleCancel"
    @ok="modalHandleOk"
  >
    <a-input
      v-model="searchQuery"
      placeholder="请输入箱号查询"
      allow-clear
      style="margin-bottom: 16px; width: 80%"
    />
    <a-button type="primary" @click="handleSearch" style="margin-left: 8px">
      查询
    </a-button>
    <a-table
      :columns="columns"
      :data="filteredTrayOptions"
      :pagination="false"
      v-model:selected-keys="selectedKeys"
      :row-selection="rowSelection"
      row-key="label"
    >
      <template #index="{ record }">{{
        filteredTrayOptions.indexOf(record) + 1
      }}</template>
    </a-table>
    <div style="display: flex; justify-content: center; margin-top: 8px">
      <a-pagination
        :total="total"
        :current="currentPage"
        :page-size="pageSize"
        show-total
        show-jumper
        show-page-size
        @change="handlePageChange"
        @update:pageSize="handleChangeSize"
      />
    </div>
  </a-modal>
</template>